import React, { useState } from 'react';
import { Select, Switch } from 'antd';

import { Input } from 'antd';
import { Button } from 'antd';
import { DatePicker } from 'antd';
import Message from '@/utils/message';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
import type { RangePickerProps } from 'antd/es/date-picker';
import { useSelector } from 'react-redux';
import { customerInvitationLinks } from '@/api';
import type { customerInvitationLinksProps } from '@/api';
import AgentService from '@/modules/Agent';
import { useTranslation } from 'react-i18next';
import styled from '@emotion/styled';
import useSyncState from '../hooks/useSyncState';

const { RangePicker } = DatePicker;

interface TransferClientProps {
	onCancel?: () => void;
}

const TransferClient = (props: TransferClientProps) => {
	const { t } = useTranslation();
	const { onCancel } = props;
	const { session, agent } = useSelector((state: any) => state);

	const [isReuseLink, setIsReuseLink] = useState<boolean>(true);

	const [link, setLink] = useState<string>('');

	const [generating, setGenerating] = useState<boolean>(false);

	const [customerName, setCustomerName] = useState<string>('');

	const [customerRole, setCustomerRole] = useState<string[]>([]);

	const [startDate, setStartDate] = useState<string>('');

	const [endDate, setEndDate] = useState<string>('');

	const [errorMessage, setErrorMessage] = useSyncState<string>('');

	const copyLink = () => {
		if (!link) return;
		let linkText = document.getElementById('link')!.innerText;
		let input: any = document.getElementById('input-link')!;
		input.value = linkText;
		input.select();
		document.execCommand('copy');
		Message.normal(t('COPY_LINK'));
	};

	const setDatePick: RangePickerProps['onChange'] = (dates, dateStrings) => {
		if (dates) {
			console.log('form:' + dateStrings[0], 'to:' + dateStrings[1]);
			setStartDate(dateStrings[0]);
			setEndDate(dateStrings[1]);
		} else {
			console.log('clear');
			setStartDate('');
			setEndDate('');
		}
	};

	const InvitationLinks = async () => {
		if (link || generating) return;
		if (customerRole.length === 0) {
			setErrorMessage('*' + t('select-client-role'));
			return;
		}
		let data: customerInvitationLinksProps = {
			bizScenId: Number(AgentService.bizScenarioId),
			org: AgentService.user?.org!,
			type: isReuseLink ? 0 : 1,
			sessionId: session.sessionId,
			customerId: customerName,
			customerRole: customerRole.toString(),
			startDate: startDate,
			endDate: endDate
		};
		setGenerating(true);
		const org = AgentService.user?.org!;
		setTimeout(async () => {
			try {
				const res = await customerInvitationLinks(data);
				if (res.status === 200) {
					setLink(AgentService.configure.customerUrl + encodeURIComponent(res.data) + `&org=${org}`);
					Message.normal(t('CREATED_LINK'));
				} else {
					Message.warning(t('CREATE_INVITE_LINK_FAILED'));
				}
				setGenerating(false);
			} catch (error: any) {
				console.log(error);
				if (error && error.data.code === 1301) {
					Message.warning(t('select-link-expiration-date'));
				} else {
					Message.warning(t('CREATE_INVITE_LINK_FAILED'));
				}
				setGenerating(false);
			} finally {
				setErrorMessage('')
			}
		}, 500);
	};

	const onChangeCustomerRole = (e: any) => {
		setCustomerRole(e);
		setErrorMessage('')
	};

	const CustomerRoleSelect = styled(Select)`
		display: block;
		height: 40px;
		background: #f6f6f6;
		border-radius: 4px;
		.ant-select-selector {
			.ant-select-selection-placeholder {
				line-height: 40px;
			}
			.ant-select-selection-item {
				line-height: 40px;
			}
		}
	`;

	const ErrorText = styled.p`
		font-size: 12px;
		color: #f8646a;
	`;

	return (
		<div className="transfer-client-contanier">
			<div className="header">
				<div className="sessionId-box">SessionID: {session.sessionId}</div>
				<div className="reuse-link-box">
					<span className="reuse-link-text">{t('whether-link-reused')}</span>
					<Switch
						checked={isReuseLink}
						onChange={() => {
							setIsReuseLink(!isReuseLink);
						}}
					// status="transfer-client"
					/>
				</div>
			</div>
			<div className="client-name-box">
				<label className="client-name-title">
					{t('client-name')} <span className="client-name-remarks">{'（' + t('optional') + '）'}</span>
				</label>
				<Input placeholder={t('input-client-name') as string} onChange={e => setCustomerName(e.target.value)} maxLength={20} bordered={false} />
			</div>
			<div className="client-role-box">
				<label className="client-role-title">{t('client-role')}</label>
				<CustomerRoleSelect
					onChange={e => onChangeCustomerRole(e)}
					placeholder={t('select-client-role') as string}
					bordered={false}
					value={customerRole}
					options={AgentService.allRoleWihtBusiness.map(item => ({ value: item.name, label: item.name }))}
				></CustomerRoleSelect>
			</div>
			{errorMessage() ? <ErrorText>{errorMessage()}</ErrorText> : undefined}
			<div className="client-role-box">
				<label className="client-role-title">
					{t('link-expiration-date')} <span className="client-role-remarks">{'（' + t('optional') + '）'}</span>
				</label>
				<RangePicker
					className="widget-range-picker"
					locale={locale}
					popupStyle={{ zIndex: '9999' }}
					separator={<span style={{ paddingRight: '24px' }}>{t('to')}</span>}
					showTime={{
						hideDisabledOptions: true,
						defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')]
					}}
					format="YYYY-MM-DD HH:mm:ss"
					placeholder={[t('begin-time'), t('end-time')]}
					onCalendarChange={setDatePick}
				// bordered={false}
				/>
			</div>
			<div className="link-box">
				{link ? (
					<p className="link" id="link">
						{link}
					</p>
				) : (
					<p className="link-remarks">{t('link-create-area')}</p>
				)}
				<p className="copy" style={{ color: link ? '' : '#CECECE' }} onClick={copyLink}>
					{t('one-click-copy')}
				</p>
			</div>
			<div className="btn-box">
				<Button
					// type="default"
					onClick={() => {
						onCancel && onCancel();
					}}
				>
					{t('cancel')}
				</Button>
				<Button type="primary" htmlType="submit" className={link || generating ? 'generated' : ''} onClick={InvitationLinks}>
					<div className="invite-btn">
						{link ? t('created') : generating ? t('creating') : t('link-created')}
						{generating ? <span className="icon-widget-icon_loding_24" /> : ''}
					</div>
				</Button>
			</div>
			<input type="text" className="input-link" id="input-link" readOnly={true} />
		</div>
	);
};

export default TransferClient;
